import { CommandType } from "./command";
import TerminalType = Terminal.TerminalType
import { commandMap } from "./commandRegister";
import getopts from "getopts";

export const doCommandExecute = async(text:string, terminal:TerminalType, parentCommand?:CommandType)=>{
    text = text.trim();
    if (!text) {
        return;
    }
    const command: CommandType = getCommand(text, parentCommand);
    if (!command) {
        terminal.writeTextErrorResult("找不到命令");
        return;
    }

    console.log(command, 'command');
    const args = text.split( ' ').slice(1);
    const options: getopts.Options = {
        alias: {},
        default: {},
        string: [],
        boolean: [],
    };
    const parsedOptions = getopts(args, options);
    await command.action(parsedOptions, terminal);
};

const getCommand= (text:string, parentCommand?:CommandType) : CommandType=>{
    let func = text.split(' ', 1)[0];
    // 大小写无关
    func = func.toLowerCase();
    let commands = commandMap;
    // 有父命令，则从父命令中查找
    if (
        parentCommand &&
    parentCommand.subCommands &&
    Object.keys(parentCommand.subCommands).length > 0
    ) {
        commands = parentCommand.subCommands;
    }
    const command = commands[func];
    return command;
};
